import { Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.svg'
import { Card } from 'antd'
import { useStore } from '@/store'
import { useNavigate } from 'react-router-dom'
import './index.scss'

function Login () {
  const { loginStore } = useStore()
  const usenavigat = useNavigate()
  const [messageApi, contextHolder] = message.useMessage()
  const onFinishFun = (values) => {
    const { mobile, code } = values
    loginStore.login({ mobile, code }).then((el) => {
      usenavigat('/', { replace: true })
      messageApi.open({
        type: 'success',
        content: '登录成功'
      })
    }).catch(err => {
      messageApi.open({
        type: 'error',
        content: err.response.data.message
      })
    })

  }
  return (
    <div className="login">
      {contextHolder}
      <Card className="login-container">
        <img className="login-logo" src={logo} alt='logo' />
        <Form validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinishFun}
          initialValues={{
            agreement: true,
            mobile: '13811111111',
            code: '246810'
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur'
              },
              {
                required: true,
                message: '请输入手机号'
              }
            ]}
          >
            <Input size="large" placeholder="13811111111" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入密码'
              },
              {
                len: 6,
                message: '请输入六位密码',
                validateTrigger: 'onBlur'
              }
            ]}>
            <Input size="large" placeholder="" />
          </Form.Item>
          <Form.Item
            name='agreement'
            valuePropName="checked"
            rules={
              [
                {
                  validator:
                    (_, value) => value ?
                      Promise.resolve() :
                      Promise.reject(new Error('请阅读并同意「用户协议」和「隐私条款」'))
                }
              ]
            }
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Login